import MyProFormUpload from "@/components/MyProFormUpload";
import request from "@/services/interceptors";
import { enumValuesAtom, labelListAtom } from "@/store/enum";
import { AddEditProps, OperationAddType } from "@/types";
import { transArrTOurl, transUrlTOArr } from "@/utils";
import { enumToSelectOptions, ExerciseTypeEnum } from "@/utils/enums";
import { PlusOutlined } from "@ant-design/icons";
import {
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormDependency,
  DrawerForm,
  ProFormList,
  ProCard,
  ProForm,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Form, message } from "antd";
import { useAtomValue } from "jotai";
import { useState } from "react";

const AddObjectiveTopic = ({ editData, onSuccess, trigger }: AddEditProps) => {
  const [form] = Form.useForm<OperationAddType>();
  const { courseList } = useAtomValue(enumValuesAtom);
  const labelList = useAtomValue(labelListAtom);
  const [bizCode, setBizCode] = useState("");

  const { runAsync: exerciseKnowledgesList, data: knowledge } = useRequest(
    request.sgks.exerciseKnowledgesCreate,
    { manual: true }
  );

  const changeType = async (value: string) => {
    exerciseKnowledgesList({ knowledgeType: +value } as any);
    form.setFieldsValue({
      knowledgeIds: [],
    });
  };

  // 显示弹窗渲染
  const onOpenChange = async (visible: boolean) => {
    if (visible) {
      if (editData) {
        const res: any = await request.sgks.exerciseGetList({
          exerciseId: editData.exerciseId,
        });
        if (res.data) {
          setBizCode(res.data.exerciseCode);
          exerciseKnowledgesList({
            knowledgeType: res.data?.exerciseType,
          } as any);
          form.setFieldsValue({
            ...res.data,
            labelIds: res.data?.labels?.map((i) => i.labelId),
            exerciseRawFile: transUrlTOArr(res.data?.exerciseRawFile),
            exerciseAnswer: transUrlTOArr(res.data?.exerciseAnswer),
            exerciseSteps: res.data?.exerciseSteps?.map((i) => {
              return {
                ...i,
                stepPics: transUrlTOArr(i?.stepPics),
                knowledgeIds: i.stepKnowledges?.map((j) => j.stepKnowledgeId),
              };
            }),
          });
        }
      } else {
        const res = await request.sgks.exerciseCodeList();
        setBizCode(res.data);
        form.setFieldsValue({
          exerciseCode: res.data,
        });
      }
    }
  };

  return (
    <DrawerForm<OperationAddType>
      onOpenChange={onOpenChange}
      title={editData ? "编辑操作题" : "新建操作题"}
      trigger={
        trigger || (
          <Button type="primary" icon={<PlusOutlined />}>
            新增
          </Button>
        )
      }
      labelCol={{ span: 4 }}
      layout="horizontal"
      width={"90%"}
      form={form}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: false,
        onClose: () => {
          form.resetFields();
        },
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        console.log(values, "最终结果");
        const newValues = {
          ...values,
          exerciseAnswer: transArrTOurl(values?.exerciseAnswer),
          exerciseRawFile: transArrTOurl(values?.exerciseRawFile),
          exerciseSteps: values?.exerciseSteps?.map((i) => {
            return {
              ...i,
              stepPics: transArrTOurl(i?.stepPics),
            };
          }),
        };
        await request.sgks.exerciseAddOrEditCreate({
          ...newValues,
          exerciseId: editData?.exerciseId,
          opt: editData ? 2 : 1,
        });
        message.success("提交成功");
        onSuccess?.();
        return true;
      }}
      onError={(err) => {
        console.log(err, "err");
      }}
    >
      <ProFormText
        disabled
        required
        name="exerciseCode"
        label="题目编号"
        rules={[{ required: true }]}
      />
      <ProFormSelect
        required
        name="exerciseType"
        label="操作题类型"
        options={enumToSelectOptions(ExerciseTypeEnum).filter(
          (i) => i.value !== 1
        )}
        onChange={changeType}
        rules={[{ required: true }]}
        disabled={!!editData?.id}
      />
      <ProFormTextArea name="exerciseInfo" label="题目标题" />
      {
        <>
          <ProFormDependency name={["exerciseType"]}>
            {({ exerciseType }) => {
              if (exerciseType) {
                return (
                  <>
                    <ProFormList
                      name={"exerciseSteps"}
                      label="操作步骤"
                      creatorButtonProps={{
                        creatorButtonText: "添加一个操作步骤",
                      }}
                      itemContainerRender={(doms) => {
                        return <ProForm.Group>{doms}</ProForm.Group>;
                      }}
                      rules={[
                        {
                          required: true,
                          validator: async (_, value) => {
                            if (value && value.length > 0) {
                              return;
                            }
                            throw new Error("至少要有一项！");
                          },
                        },
                      ]}
                    >
                      {(f, index, action) => {
                        return (
                          <ProCard
                            bordered
                            title={`步骤${index + 1}`}
                            style={{
                              marginBlockEnd: 8,
                              flexDirection: "column",
                              minWidth: "600px",
                            }}
                          >
                            <ProFormTextArea
                              className="!min-w-[400px] shrink-0"
                              rules={[{ required: true }]}
                              label="步骤描述"
                              name="stepDesc"
                            />
                            {exerciseType === ExerciseTypeEnum.基本操作 && (
                              <>
                                <ProFormSelect
                                  className="!min-w-[400px] shrink-0"
                                  rules={[{ required: true }]}
                                  name="knowledgeIds"
                                  label="知识点"
                                  mode="multiple"
                                  onChange={(val) => {
                                    const initVal = val?.map?.((item, idx) => {
                                      const knowledgeItem =
                                        knowledge?.data?.find((i) => {
                                          return i.knowledgeId === item;
                                        });
                                      return {
                                        knowledgeId: item,
                                        knowledgeOrder: idx,
                                        knowledgeDesc:
                                          knowledgeItem?.knowledgeDesc,
                                        parameterValues:
                                          knowledgeItem?.parameters?.map(
                                            (j, paramIdx) => {
                                              return {
                                                ...j,
                                                parameterValue: "",
                                              };
                                            }
                                          ),
                                      };
                                    });
                                    const rowData = action.getCurrentRowData();
                                    action.setCurrentRowData({
                                      ...rowData,
                                      stepKnowledges: initVal,
                                      text: 1,
                                    });
                                  }}
                                  options={knowledge?.data?.map((item) => {
                                    return {
                                      label: item.knowledgeDesc,
                                      value: item.knowledgeId,
                                    };
                                  })}
                                />
                                <ProFormList
                                  name={"stepKnowledges"}
                                  itemContainerRender={(doms) => {
                                    return (
                                      <ProForm.Group>{doms}</ProForm.Group>
                                    );
                                  }}
                                  creatorButtonProps={false}
                                  deleteIconProps={false}
                                  copyIconProps={false}
                                >
                                  {(f, index, action) => {
                                    const item = action.getCurrentRowData();
                                    return (
                                      <div className="flex flex-col">
                                        <div>
                                          知识点
                                          {index + 1}.{item?.knowledgeDesc}
                                        </div>
                                        <br />
                                        <ProFormList
                                          name={["parameterValues"]}
                                          creatorButtonProps={false}
                                          deleteIconProps={false}
                                          copyIconProps={false}
                                          itemContainerRender={(doms) => {
                                            return (
                                              <div className="inline-flex">
                                                {doms}
                                              </div>
                                            );
                                          }}
                                        >
                                          {(f, index, action) => {
                                            const item =
                                              action.getCurrentRowData();
                                            return (
                                              <ProFormText
                                                rules={[{ required: true }]}
                                                placeholder={`参数${index}:${item.parameterName}`}
                                                name={["parameterValue"]}
                                              />
                                            );
                                          }}
                                        </ProFormList>
                                      </div>
                                    );
                                  }}
                                </ProFormList>
                              </>
                            )}

                            <MyProFormUpload
                              name="stepPics"
                              label="步骤配图"
                              fieldProps={{
                                multiple: true,
                                maxCount: 4,
                                data: {
                                  bizCode: bizCode,
                                },
                              }}
                            />
                          </ProCard>
                        );
                      }}
                    </ProFormList>
                  </>
                );
              }
            }}
          </ProFormDependency>
        </>
      }
      <ProFormTextArea required name="exercisePrompt" label="解析" />
      <MyProFormUpload
        title="上传"
        name="exerciseRawFile"
        label="原始素材"
        fieldProps={{
          data: {
            bizCode: bizCode,
          },
        }}
        rules={[{ required: true }]}
      />
      <MyProFormUpload
        title="上传"
        name="exerciseAnswer"
        label="答案文件"
        fieldProps={{
          data: {
            bizCode: bizCode,
          },
        }}
        rules={[{ required: true }]}
      />

      <ProFormSelect
        name="courseId"
        label="所属课程"
        options={courseList}
        rules={[{ required: true }]}
      />
      <ProFormSelect
        name="labelIds"
        mode="multiple"
        label="标签"
        options={labelList}
        rules={[{ required: true }]}
      />
    </DrawerForm>
  );
};

export default AddObjectiveTopic;
